package com.mengfou.hello;

import com.android.build.gradle.AppExtension;
import com.android.build.gradle.api.ApplicationVariant;
import com.android.build.gradle.tasks.PackageApplication;
import com.mengfou.task.HelloTask;
import com.mengfou.task.TaskHelper;
import org.gradle.api.Action;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;

import java.util.List;

/**
 * @author 梦否
 * @date 2022/12/09 17:26
 */
public class HelloPlugin implements Plugin<Project> {

    @Override
    public void apply(Project project) {
        project.getLogger().info("------------------configure----------------------");

        project.afterEvaluate(new Action<Project>() {
            @Override
            public void execute(Project project) {
                AppExtension appExtension = project.getExtensions().getByType(AppExtension.class);
                for (ApplicationVariant applicationVariant : appExtension.getApplicationVariants()) {
                    String variantName = applicationVariant.getName();
                    Task beforeTask = TaskHelper.findTaskByName(project, "compileDebugJavaWithJavac", variantName);
                    HelloTask task = project.getTasks().create(getTaskName(variantName), HelloTask.class);
                    task.dependsOn(beforeTask);
                    List<Task> tasks = TaskHelper.findTaskByName(project, PackageApplication.class, variantName);
                    for (Task systemTask : tasks) {
                        systemTask.dependsOn(task);
                    }
                }
            }
        });
    }

    private String getTaskName(String variantName) {
        variantName = variantName.substring(0, 1).toUpperCase() + variantName.substring(1);
        return "hello" + variantName + "PluginDemo";
    }
}
